export async function render(paths: string) {
    const val = get(paths.split('/').filter(it => !!it), window)
    if (val?.render) return val.render()
    const [scope, addon, ...others] = paths.split('/').filter(it => !!it)
    const main = `/@${scope}/${addon}/dist/public/${others.filter(it => !!it).join('/')}.js`
    return await loadScript(`/${paths.split('/').filter(it => !!it).join('/')}`, main)
}
export const navigationTo = render;

const loadScript = (link: string, main: string) => {
    return new Promise<any>((resolve, reject) => {
        const script = document.createElement('script') as HTMLScriptElement;
        script.src = main + `?t=${Date.now()}`;
        script.type = 'module';
        script.onload = () => {
            const val = get(link.split('/').filter(it => !!it), window)
            if (val?.render) return resolve(val.render())
            reject(new Error(`不规范的组件，请参考相关文档开发`))
        }
        script.onerror = (e) => {
            reject(e)
        }
        document.body.appendChild(script)
    })
}

function get(paths: string[], val: any) {
    if (paths.length <= 0) return val;
    const [path, ...other] = paths;
    const has = Reflect.has(val, path)
    if (has) {
        return get(other, Reflect.get(val, path))
    }
}